package com.itheima.app.manager;


import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.im.HuanXinTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.service.db.UsersService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Duration;


@Component
public class UsersManager {
    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UsersService usersService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;



    /**
     * 发送短信验证码
     * @param phone
     */
    public void sendMsg(String phone) {
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));
    }


    /**
     * 校验手机号
     * @param phone
     * @param code
     * @return
     */
    public Boolean checkVerificationCode(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            return false;
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        return true;

    }

    /**
     * 更新手机号
     * @param phone
     */
    public void updateVerificationInfo(String phone) {
        User user = UserHolder.get();
        user.setMobile(phone);
        UserHolder.remove();
        UserHolder.set(user);
        usersService.update(user);
    }

}
